<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright   Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
/* @var $this \Magento\ConfigurableProduct\Block\Product\Configurable\AttributeSelector */
?>
<script type="text/javascript">
(function($){
    var $form;

    require([
        "jquery",
        "jquery/ui",
        "Magento_ConfigurableProduct/catalog/product-variation"
    ], function($){
        'use strict';

        $form = $('#affected-attribute-set-form');

        var resetValidation = function() {
            $form.find('.messages .message.error').hide();
            $form.find('form').validation().data('validator').resetForm();
        };

        $('[data-form=edit-product]').append($('<input>', {
            type: 'hidden',
            name: 'new-variations-attribute-set-id',
            id: 'new-variations-attribute-set-id'
        }));

        $form
            .dialog({
                title: '<?php echo __('Choose Affected Attribute Set'); ?>',
                autoOpen: false,
                id: '<?php echo $this->getJsId() ?>',
                minWidth: 700,
                modal: true,
                resizable: false,
                close: resetValidation,
                buttons: [{
                    text: '<?php echo __('Cancel'); ?>',
                    id: '<?php echo $this->getJsId('close-button') ?>',
                    click: function() {
                        $form.dialog('close');
                    }
                }, {
                    text: '<?php echo __('Confirm'); ?>',
                    id: '<?php echo $this->getJsId('confirm-button') ?>',
                    'class': 'primary',
                    click: function() {
                        if ($form.find('input[name=affected-attribute-set]:checked').val() == 'current') {
                            $('#new-variations-attribute-set-id').val($('#attribute_set_id').val());
                            $form.dialog('close')
                                .data('target').click();
                            return;
                        }

                        $form.find('.messages .message.error').hide();
                        if (!$form.find('form').validation().valid()) {
                            $form.find('input[name=new-attribute-set-name]').focus();
                            return false;
                        }

                        $.ajax({
                            type: 'POST',
                            url: '<?php echo $this->getAttributeSetCreationUrl()?>',
                            data: {
                                gotoEdit: 1,
                                attribute_set_name: $form.find('input[name=new-attribute-set-name]').val(),
                                skeleton_set: $('#attribute_set_id').val(),
                                form_key: '<?php echo $this->getFormKey()?>',
                                return_session_messages_only: 1
                            },
                            dataType: 'json',
                            showLoader: true,
                            context: $form
                        })
                            .success(function (data) {
                                if (!data.error) {
                                    $('#new-variations-attribute-set-id').val(data.id);
                                    $form.dialog('close')
                                        .data('target').click();
                                } else {
                                    $form.find('.messages .message.error').replaceWith($(data.messages).find('.message.error'));
                                }
                            });

                        return false;
                    }
                }]
            })
            .find('input[name=affected-attribute-set]').on('change', function() {
                $('#affected-attribute-set-new-name-container')[$(this).val() == 'new' ? 'show' : 'hide']();
                resetValidation();
                if ($(this).val() == 'new') {
                    $form.find('input[name=new-attribute-set-name]').focus();
                }
            });
    });
    
    /**
     * This fix was made in order to properly handle 'stopImmediatePropagation'.
     */
    $('#save-split-button .item').on('click', function(event) {
        if ($('#new-variations-attribute-set-id').val() != '') {
            return; // affected attribute set was already chosen
        }
        
        var extendingAttributes = [];

        $.each($('#configurable-attributes-container').variationsAttributes('getAttributes'), function () {
            if (!$('#attribute-' + this.code + '-container').length) {
                extendingAttributes.push(this.id);
            }
        });
        if (!extendingAttributes.length) {
            $('#new-variations-attribute-set-id').val($('#attribute_set_id').val());
            return; // all selected configurable attributes belong to current attribute set
        }
        if (!$('[data-role=product-variations-matrix] [data-column=entity_id]:checked')
            .closest('tr').has('input[name$="[name]"]').length
        ) {
            return; // no new simple products to save from matrix: uniting attribute set is not needed
        }

        event.stopImmediatePropagation();

        $form.data('target', event.target)
            .dialog('open');
    });

})(jQuery);
</script>
